import requests
from lxml import etree

url = "http://www.weather.com.cn/weather/101270101.shtml"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
html = response.content.decode("utf-8")

html_tree = etree.HTML(html)
li_list = html_tree.xpath('//ul[@class="t clearfix"]/li')[:7]

result = []
for li in li_list:
    try:
        # 提取日期
        date = li.xpath('.//h1/text()')[0].replace("日", "") + "日"
        
        # 提取天气
        weather = li.xpath('.//p[@class="wea"]/text()')[0]
        
        # 修复温度提取逻辑（处理最高温/最低温分开展示的情况）
        temp_elements = li.xpath('.//p[@class="tem"]//text()')
        temp = "".join(temp_elements).replace("°", "").strip()  # 合并文本并清理符号
        
        result.append(f"日期：{date}，天气：{weather}，温度：{temp}")
    except Exception as e:
        print(f"数据提取失败：{e}")
        continue

# 保存结果
with open("resultPath.txt", "w", encoding="utf-8") as f:
    f.write("".join(result))